package com.kfm.servlet.day04;

import com.kfm.servlet.day04.db.DBUtils;
import com.kfm.servlet.day04.model.FileModel;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/filelist")
public class FileListServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取所有的文件
        DBUtils<FileModel> dbUtils = new DBUtils<>(1);

        String sql = "select id, path, type, name, size, upload_time from file";
        List<FileModel> select = dbUtils.select(sql, FileModel.class);

        // 写 html 页面
        resp.setContentType("text/html;charset=utf-8");
        StringBuilder sb = new StringBuilder("""
                <!DOCTYPE html>
                <html lang="en">
                <head>
                    <meta charset="UTF-8">
                    <title>文件列表</title>
                </head>
                <body>
                    <table border="1" width="800px">
                        <tr>
                            <th>序号</th>
                            <th>文件名</th>
                            <th>文件大小</th>
                            <th>文件类型</th>
                            <th>上传时间</th>
                            <th>操作</th>
                        </tr>
                        """);

        for (int i = 0; i < select.size(); i ++) {
            FileModel fileModel = select.get(i);
            sb.append("<tr>");
            sb.append("<td>").append(i + 1).append("</td>");
            sb.append("<td>").append(fileModel.getName()).append("</td>");
            sb.append("<td>").append(Math.ceil(fileModel.getSize() / 1024.0) + "kb").append("</td>");
            sb.append("<td>").append(fileModel.getType()).append("</td>");
            sb.append("<td>").append(fileModel.getUploadTime()).append("</td>");
            sb.append("<td>");
            sb.append("<a href=\"downloadv2?id=").append(fileModel.getId()).append("\">下载</a>");
            sb.append("</td>");
            sb.append("</tr>");
        }
        sb.append("</table>");
        sb.append("</body>");
        sb.append("</html>");

        resp.getWriter().write(sb.toString());

    }
}
